<template>
  <div style="font-size: 14px">
    <!-- 事件详情弹窗 -->
    <el-drawer v-model="dialogVisible" title="事件详情" direction="rtl" size="1080">
      <div v-loading="loading">
        <div
          class="btns"
          v-if="
            !loading &&
            details.eno &&
            !userStore.userInfo.roleCode.includes('ROLE_ENDUSER') &&
            userStore.userInfo.job != '终端用户'
          "
        >
          <span>操作：</span>
          <div class="flex-1">
            <el-button type="primary" v-if="details.statusCode == 'request_close'" @click="showRequestActionMask('reopen')">
              流程重新开启
            </el-button>
            <template v-if="details.statusCode != 'request_close'">
              <!-- @click="showRequestActionMask('notComprehensiveNotSubmitted')" -->
              <el-button
                type="primary"
                v-if="details.statusCode == 'request_new' || details.statusCode == 'request_processReopen'"
                @click="processOutcome('请求退回')"
              >
                请求退回
              </el-button>
              <!--  -->
              <el-button
                type="primary"
                v-if="details.statusCode == 'request_notComprehensiveNotSubmitted'"
                @click="showRequestActionMask('reSubmit')"
              >
                描述完成重新提交
              </el-button>
              <!-- v-if="
                  details.statusCode == 'request_new' ||
                  details.statusCode == 'request_two' ||
                  !details.statusCode ||
                  details.statusCode == ''
                " -->
              <el-button
                type="primary"
                v-if="
                  details.statusCode != 'request_awaiting' &&
                  details.statusCode != 'request_complete' &&
                  details.statusCode != 'request_notComprehensiveNotSubmitted'
                "
                @click="showRequestActionMask('requestHangRemove')"
              >
                挂起
              </el-button>
              <el-button
                type="primary"
                v-if="details.statusCode == 'request_awaiting' && userStore.userInfo.roleCode.includes('ROLE_SYSADMIN')"
                @click="showRequestActionMask('requestHangRemove')"
              >
                解除挂起
              </el-button>
              <!-- {{
                (details.statusCode === "request_new" || details.statusCode == "request_processReopen") &&
                details.assigneeName === ""
              }} -->
              <el-button
                type="primary"
                v-if="
                  (details.statusCode === 'request_new' || details.statusCode == 'request_processReopen') &&
                  details.assigneeName === ''
                "
                @click="showRequestActionMask('requestGet')"
              >
                请求提取
              </el-button>
              <el-button
                type="primary"
                v-if="processDetailData.assignee === '' && processIsMyGroup"
                @click="showRequestActionMask('taskGet')"
              >
                任务提取
              </el-button>
              <el-button type="primary" v-if="processDetailData.assignee" @click="taskReassignmentMask = true">
                任务重新指派
              </el-button>
              <!-- {{ details.assigneeNo === userStore.userInfo.userId }} -->
              <template v-if="details.assigneeNo === userStore.userInfo.userId">
                <el-button
                  type="primary"
                  v-if="(details.statusCode === 'request_new' || details.responsesTime === '') && details.flowStart == false"
                  @click="showOpenProcessMask"
                >
                  开启流程
                </el-button>
                <template v-if="details.statusCode != 'request_awaiting' && processDetailData.assignee != ''">
                  <el-button type="primary" v-for="item in processDetailData.outcomes" :key="item" @click="processOutcome(item)">
                    {{ item }}
                  </el-button>
                </template>
                <!-- <el-button
                  type="primary"
                  v-if="!details.statusCode || details.statusCode == ''"
                  @click="showProcessingCompletedMask"
                >
                  处理完成
                </el-button>
                <el-button
                  type="primary"
                  v-if="!details.statusCode || details.statusCode == ''"
                  @click="showAssignTechniciansMask"
                >
                  指派其他技术员处理
                </el-button> -->
              </template>
            </template>
          </div>
          <el-dropdown>
            <div class="el-dropdown-link">
              <el-button type="primary" plain>
                <span>更多操作</span>
                <el-icon class="el-icon--right">
                  <arrow-down />
                </el-icon>
              </el-button>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item v-if="details.statusCode != 'request_close'" @click="showSendMailMask">
                  邮件回复
                </el-dropdown-item>
                <!--  -->
                <div v-auth="'request_detail_flowTrack'">
                  <el-dropdown-item v-if="details.processKey" @click="seeFlowChart">流程跟踪</el-dropdown-item>
                </div>
                <div>
                  <el-dropdown-item  @click="seeRequestService">请求服务单</el-dropdown-item>
                </div>
                <div v-auth="'request_manage_getProblem'">
                  <el-dropdown-item @click="showAddProblemMask">请求升级成问题</el-dropdown-item>
                </div>
                <div v-auth="'request_manage_getChange'">
                  <el-dropdown-item v-if="details.statusCode != 'request_close'" @click="showAddChangeMask">
                    请求升级为变更
                  </el-dropdown-item>
                </div>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
        <div class="title">基本信息</div>
        <div v-if="showCustomerForm == true">
          <form-create v-model="formData" :option="option" :rule="formCreateRules" />
          <el-form style="width: 100%" label-width="122px">
            <el-form-item label="描述 :">
              <WangEditor
                v-if="edescFlag == true"
                v-model:value="customerContent"
                width="1200px"
                height="400px"
                ref="cwangEditor"
              />
            </el-form-item>
          </el-form>
          <form-create v-model="formData" :option="option2" :rule="formCreateRules2" class="custom-tree2" />
        </div>
        <div v-if="showCustomerForm == false">
          <div class="table-data-box">
            <div class="data-cell row">
              <span class="label">标题</span>
              <span class="content">{{ details.etitle }}</span>
            </div>
            <div class="data-cell row">
              <span class="label">描述</span>
              <div class="content">
                <div v-html="details.edesc"></div>
              </div>
            </div>
            <div class="data-cell">
              <span class="label">编号</span>
              <span class="content">{{ details.requestCode }}</span>
            </div>
            <div class="data-cell">
              <span class="label">关联服务</span>
              <span class="content">{{ details.requestServiceDirName }}</span>
            </div>
            <div class="data-cell">
              <span class="label">所属客户</span>
              <span class="content">{{ details.companyName }}</span>
            </div>
            <div class="data-cell">
              <span class="label">请求用户</span>
              <div class="content">
                <el-link type="primary" @click="showUserInfoMask">{{ details.createdByName }}</el-link>
              </div>
            </div>
            <div class="data-cell">
              <span class="label">请求分类</span>
              <span class="content">{{ details.requestCategoryName }}</span>
            </div>
            <div class="data-cell">
              <span class="label">来源</span>
              <span class="content">{{ details.imodeName }}</span>
            </div>
            <div class="data-cell">
              <span class="label">优先级</span>
              <div class="content">
                <span
                  v-if="details.priorityColor"
                  :style="{ background: details.priorityColor }"
                  style="padding: 0 8px; color: #ffffff"
                >
                  {{ details.priorityName }}
                </span>
                <span v-else>{{ details.priorityName }}</span>
              </div>
            </div>
            <div class="data-cell">
              <span class="label">影响</span>
              <div class="content">
                <span
                  v-if="details.effectRangeColor"
                  :style="{ background: details.effectRangeColor }"
                  style="padding: 0 8px; color: #ffffff"
                >
                  {{ details.effectRangeName }}
                </span>
                <span v-else>{{ details.effectRangeName }}</span>
              </div>
            </div>
            <div class="data-cell">
              <span class="label">复杂程度</span>
              <span class="content">{{ details.levelName }}</span>
            </div>
            <div class="data-cell">
              <span class="label">紧急度</span>
              <div class="content">
                <span
                  v-if="details.seriousnessColor"
                  :style="{ background: details.seriousnessColor }"
                  style="padding: 0 8px; color: #ffffff"
                >
                  {{ details.seriousnessName }}
                </span>
                <span v-else>{{ details.seriousnessName }}</span>
              </div>
            </div>
            <div class="data-cell">
              <span class="label">位置</span>
              <span class="content">{{ details.locationName }}</span>
            </div>
            <div class="data-cell">
              <span class="label">升级到</span>
              <span class="content"></span>
            </div>
            <div class="data-cell">
              <span class="label">指派到工作组</span>
              <span class="content">{{ details.assigneeGroupName }}</span>
            </div>
            <div class="data-cell">
              <span class="label">指派到技术员</span>
              <span class="content">{{ details.assigneeName }}</span>
            </div>
          </div>
        </div>
        <el-tabs v-model="tabName" class="demo-tabs">
          <el-tab-pane label="详细信息" name="info">
            <div class="table-data-box">
              <div class="data-cell">
                <span class="label">状态</span>
                <div class="content">
                  <span
                    v-if="details.statusColor"
                    :style="{ background: details.statusColor }"
                    style="padding: 0 8px; color: #ffffff"
                  >
                    {{ details.statusName }}
                  </span>
                  <span v-else>{{ details.statusName }}</span>
                </div>
              </div>
              <div class="data-cell">
                <span class="label">服务级别</span>
                <span class="content">{{ details.slaLevelName }}</span>
              </div>
              <div class="data-cell">
                <span class="label">SLA响应时间</span>
                <span class="content">{{ details.maxResponsesTime }}</span>
              </div>
              <div class="data-cell">
                <span class="label">SLA完成时间</span>
                <span class="content">{{ details.maxCompletesTime }}</span>
              </div>
              <div class="data-cell">
                <span class="label">SLA协议已过期</span>
                <span class="content color-red" v-if="details.slaExpired">是</span>
                <span class="content" v-else>否</span>
              </div>
              <div class="data-cell">
                <span class="label">创建时间</span>
                <span class="content">{{ details.createdOn }}</span>
              </div>
              <div class="data-cell">
                <span class="label">实际响应时间</span>
                <span class="content">{{ details.responsesTime }}</span>
              </div>
              <div class="data-cell">
                <span class="label">实际完成时间</span>
                <span class="content">{{ details.closeTime }}</span>
              </div>
              <div class="data-cell">
                <span class="label">发生位置</span>
                <span class="content"></span>
              </div>
              <div class="data-cell">
                <span class="label">详细坐标</span>
                <span class="content">
                  {{ parseFloat(details.longitude || 0).toFixed(1) }},{{ parseFloat(details.latitude || 0).toFixed(1) }}
                </span>
              </div>
            </div>
          </el-tab-pane>
          <!-- 附件 -->
          <el-tab-pane label="附件" name="enclosure">
            <EnclosureList
              v-if="tabHistory.indexOf('enclosure') >= 0"
              :eno="details.eno"
              event-type="itsm.request"
            ></EnclosureList>
          </el-tab-pane>
          <!-- 流程历史仼务 -->
          <el-tab-pane label="流程历史任务" name="processHistoryTasks" v-if="details.pid">
            <ProcessHistoryTasksBox
              v-if="tabHistory.indexOf('processHistoryTasks') >= 0"
              :pid="details.pid"
            ></ProcessHistoryTasksBox>
          </el-tab-pane>
          <!-- 历史记录 -->
          <div v-auth="'VIEW_REQUEST_HISTORYRECORD_RES'">
            <el-tab-pane label="历史记录" name="historicalRecords">
              <HistoricalRecordsBox
                v-if="tabHistory.indexOf('historicalRecords') >= 0"
                :eno="details.eno"
                event-type="itsm.request"
              ></HistoricalRecordsBox>
            </el-tab-pane>
          </div>

          <!-- 任务 -->
          <el-tab-pane label="任务" name="task">
            <TaskListBox v-if="tabHistory.indexOf('task') >= 0" :eno="details.eno" event-type="itsm.request"></TaskListBox>
          </el-tab-pane>
          <!-- 解决方案 -->
          <div v-auth="'VIEW_REQUEST_SOLUTIONS_RES'">
            <el-tab-pane label="解决方案" name="solution">
              <template v-if="details.statusCode == 'request_close'">
                <div class="table-data-box" v-if="details.offmodeNo">
                  <div class="data-cell row">
                    <span class="label">处理方式编号</span>
                    <span class="content">{{ details.offmodeNo }}</span>
                  </div>
                  <div class="data-cell row">
                    <span class="label">处理方式</span>
                    <span class="content">{{ details.offmodeName }}</span>
                  </div>
                  <div class="data-cell row">
                    <span class="label">方案描述</span>
                    <span class="content" v-html="details.solutions"></span>
                  </div>
                </div>
                <div v-else>暂无解决方案</div>
              </template>
              <div v-else style="width: 55%; padding: 15px; border: 1px solid #e5e5e5; border-radius: 10px">
                <el-form label-width="80">
                  <el-form-item label="处理方式">
                    <el-select
                      v-model="solutionForm.offmodeNo"
                      :disabled="details.offmodeNo ? true : false"
                      placeholder="请选择处理方式"
                      style="width: 240px"
                    >
                      <el-option v-for="item in handlingMethodList" :key="item.dcode" :label="item.dname" :value="item.dcode" />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="方案描述">
                    <el-input type="textarea" v-model="solutionForm.content" :rows="4" placeholder="方案描述" />
                  </el-form-item>
                  <el-form-item label="">
                    <el-button type="primary" @click="solutionSubmit">保存</el-button>
                  </el-form-item>
                </el-form>
              </div>
            </el-tab-pane>
          </div>
          <!-- 历史邮件 -->
          <div v-auth="'VIEW_HISTORYEMAIL_RES'">
            <el-tab-pane label="历史邮件" name="email">
              <EmailListBox
                v-if="tabHistory.indexOf('email') >= 0"
                :eno="details.eno"
                :request-code="details.requestCode"
              ></EmailListBox>
            </el-tab-pane>
          </div>
        </el-tabs>
      </div>
    </el-drawer>
    <!-- 请求退回/挂起/请求提取 -->
    <el-dialog v-model="requestActionMask" :title="requestActionMaskTitle" width="600">
      <div v-loading="requestActionLoading">
        <el-form>
          <el-form-item label="备注">
            <el-input type="textarea" v-model="requestActionForm.logDetails" :rows="5" placeholder="请输入备注" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div>
          <el-button :disabled="requestActionLoading" @click="requestActionMask = false">取消</el-button>
          <el-button :disabled="requestActionLoading" type="primary" @click="requestActionSubmit(requestActionMaskTitle)">
            发送
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 开启流程 -->
    <el-dialog title="开启流程" v-model="openProcessMask" width="600">
      <div v-loading="openProcessLoading">
        <el-form label-width="98">
          <el-form-item label="流程备注">
            <el-input type="textarea" v-model="openProcessForm.remark" :rows="5" placeholder="请输入流程备注" />
          </el-form-item>
          <el-form-item label="通知指定邮箱">
            <el-input v-model="openProcessForm.emailAddress" placeholder="请输入通知指定邮箱" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div>
          <el-button :disabled="openProcessLoading" @click="openProcessMask = false">取消</el-button>
          <el-button :disabled="openProcessLoading" type="primary" @click="openProcessSubmit">开启流程</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 处理完成 -->
    <el-dialog title="处理完成" v-model="processingCompletedMask" width="600">
      <div v-loading="processingCompletedLoading">
        <el-form label-width="98">
          <el-form-item label="处理备注">
            <el-input type="textarea" v-model="processingCompletedForm.remark" :rows="5" placeholder="请输入处理备注" />
          </el-form-item>
          <el-form-item label="通知指定邮箱">
            <el-input v-model="processingCompletedForm.emailAddress" placeholder="请输入通知指定邮箱" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div>
          <el-button :disabled="processingCompletedLoading" @click="processingCompletedMask = false">取消</el-button>
          <el-button :disabled="processingCompletedLoading" type="primary" @click="processingCompletedSubmit">提交</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 邮件回复 -->
    <el-dialog title="邮件回复" v-model="sendMailMask" width="700px">
      <div v-loading="emailLoading">
        <el-form label-width="80">
          <el-form-item label="收件邮箱">
            <el-input v-model="emailForm.receiveAddress" placeholder="请输入收件邮箱" />
            <div>有多个地址要输入时,请以分号(;)隔开</div>
          </el-form-item>
          <el-form-item label="邮件主题">
            <el-input v-model="emailForm.subject" placeholder="请输入邮件主题" />
          </el-form-item>
          <el-form-item label="邮件内容">
            <el-input type="textarea" v-model="emailForm.content" :rows="5" placeholder="请输入邮件内容" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div>
          <el-button :disabled="emailLoading" @click="sendMailMask = false">取消</el-button>
          <el-button :disabled="emailLoading" type="primary" @click="sendEmail">发送</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 任务重新指派弹窗 -->
    <el-dialog v-if="dialogVisible" v-model="taskReassignmentMask" title="任务重新指派" width="550">
      <div v-loading="taskReassignmentLoading">
        <el-form label-width="75">
          <el-form-item label="技术员" required>
            <div style="display: flex; width: 100%">
              <el-input style="flex: 1; overflow: hidden" v-model="assigneeName" placeholder="请选择技术员"></el-input>
              <el-button style="margin-left: 10px" type="primary" :icon="Search" @click="selectUser('assigneeNo')"></el-button>
            </div>
          </el-form-item>
          <el-form-item label="处理备注">
            <el-input type="textarea" v-model="taskReassignmentForm.remark" :rows="4" placeholder="请输入备注" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button :disabled="taskReassignmentLoading" @click="taskReassignmentMask = false">取消</el-button>
        <el-button :disabled="taskReassignmentLoading" type="primary" @click="taskReassignmentSubmit">提交</el-button>
      </template>
    </el-dialog>
    <!-- 指派其他技术员处理弹窗 -->
    <el-dialog v-model="assignTechniciansMask" :title="assignText" width="550">
      <div v-loading="assignTechniciansLoading">
        <el-form label-width="98">
          <el-form-item label="备注">
            <el-input type="textarea" v-model="assignTechniciansForm.remark" :rows="3" placeholder="请输入备注" />
          </el-form-item>
          <!-- <el-form-item label="技术组">
            <el-cascader v-model="assignTechniciansGroupName" :options="groupList" :show-all-levels="false" style="width: 100%" :props="props1" @update:model-value="getVal"/>
          </el-form-item> -->
          <el-form-item label="指派组">
              <div style="display: flex; width: 100%">
                <el-input
                  style="flex: 1; overflow: hidden"
                  v-model="assigneeGroupName"
                  placeholder="请选择指派组"
                  :readonly="true"
                   clearable
                ></el-input>
                <el-button
                  style="margin-left: 10px"
                  type="primary"
                  :icon="Search"
                  @click="selectDepartment('filterForm.assigneeGroupNo', '请选择指派组')"
                ></el-button>
              </div>
            </el-form-item>
          <el-form-item label="技术员">
            <div style="display: flex; width: 100%">
              <el-input
                style="flex: 1; overflow: hidden"
                v-model="assignTechniciansForm.assigneeName"
                placeholder="请选择技术员"
                readonly
              ></el-input>
              <el-button style="margin-left: 10px" type="primary" :icon="Search" @click="selectUser('technicianNo')"></el-button>
            </div>
          </el-form-item>
          <el-form-item label="通知指定邮箱">
            <el-input v-model="assignTechniciansForm.emailAddress" placeholder="请输入通知指定邮箱" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="assignTechniciansMask = false">取消</el-button>
        <el-button type="primary" @click="assignTechniciansSubmit">提交</el-button>
      </template>
    </el-dialog>
    <!-- 查看流程图片弹窗 -->
    <el-dialog v-if="dialogVisible" v-model="flowChartMask" title="流程图" width="1000px">
      <!-- <img class="liu-cheng-img" :src="flowChartUrl" alt="" /> -->
      <div v-html="flowImg"></div>
    </el-dialog>
    <!-- 请求服务单 -->
    <el-dialog v-model="requestServiceMask" title="现场技术服务单" width="1200">
      <div class="service-form-container">
        <!-- 标题和编号 -->
        <div class="form-header">
          <h2>现场技术服务单</h2>
          <div class="form-number">
            <span>编号: {{ serviceFormData.documentNumber || 'N240801005' }}</span>
          </div>
        </div>
        <!-- 基本信息 -->
        <div class="form-section">
          <h3>基本信息</h3>
          <el-table :data="[serviceFormData]" border class="info-table" >
            <el-table-column prop="reporter" label="报修用户"  />
            <el-table-column prop="userGroup" label="用户分组"  />
            <el-table-column prop="contactInfo" label="联系方式"  />
          </el-table>
          <el-table :data="[serviceFormData]" border class="info-table">
            <el-table-column prop="location" label="位置" />
            <el-table-column prop="expectedArrivalTime" label="期望到场时间" />
          </el-table>
          <el-table :data="[serviceFormData]" border class="info-table">
            <el-table-column prop="serviceCatalog" label="服务目录" />
            <el-table-column prop="slaLevel" label="SLA等级"  />
          </el-table>
          <el-table :data="[serviceFormData]" border class="info-table">
            <el-table-column prop="responseTime" label="响应时间" />
            <el-table-column prop="responder" label="响应人" />
          </el-table>
          <el-table :data="[serviceFormData]" border class="info-table">
            <el-table-column prop="completionTime" label="完成时间" />
            <el-table-column prop="handler" label="处理人" />
            <el-table-column prop="handlingMethod" label="处理方式" />
          </el-table>
        </div>

        <!-- 现象描述 -->
        <div class="form-section">
          <h3>现象描述</h3>
          <el-table :data="[serviceFormData]" border class="info-table">
            <el-table-column prop="problemDescription" label="现象描述">
              <template #default="scope">
                <div v-html="scope.row.problemDescription"></div>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 过程记录 -->
        <div class="form-section">
          <h3>过程记录</h3>
          <el-table :data="serviceFormData.processRecords" border class="info-table">
            <el-table-column prop="logTitle" label="节点" />
            <el-table-column prop="createdTime" label="时间" />
            <el-table-column prop="operator" label="人员"/>
            <el-table-column prop="logDetails" label="处理记录">
              <template #default="scope">
                <div v-html="scope.row.logDetails"></div>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 关联资源资产 -->
        <div class="form-section">
          <h3>关联资源资产</h3>
          <el-table :data="serviceFormData.relatedAssets" border class="info-table">
            <el-table-column prop="categoryName" label="类型" />
            <el-table-column prop="ciname" label="名称" />
            <el-table-column prop="loc" label="位置" />
          </el-table>
        </div>

        <!-- 用户反馈 -->
        <div class="form-section">
          <h3>用户对工程师服务的意见和建议</h3>
          <el-table :data="[serviceFormData]" border class="info-table">
            <el-table-column prop="problemResolved" label="您的问题是否得到解决?">
              <template #default="scope">
                <div v-html="scope.row.problemResolved"></div>
              </template>
            </el-table-column>
            <el-table-column prop="overallRating" label="总体评分"  />
            <el-table-column prop="attitudeRating" label="态度评分"  />
            <el-table-column prop="skillRating" label="技能评分"  />
            <el-table-column prop="otherComments" label="其他意见或建议" />
          </el-table>
        </div>

        <!-- 签名部分 -->
        <div class="form-section">
          <h3>签名</h3>
          <el-table :data="[serviceFormData]" border class="info-table">
            <el-table-column prop="userDepartment" label="用户单位或部门" />
            <el-table-column prop="userSignature" label="用户签名(日期)" />
            <el-table-column prop="serviceUnit" label="服务单位" />
            <el-table-column prop="engineerSignature" label="工程师签名(日期)" />
          </el-table>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="requestServiceMask = false">关闭</el-button>
          <!-- <el-button type="primary" @click="saveServiceForm">保存</el-button> -->
          <el-button type="success" @click="printServiceForm">打印</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 请求升级成问题 -->
    <AddProblemMask v-if="dialogVisible" ref="addProblemMask" type="upgrade" @add="upgradeChange"></AddProblemMask>
    <!-- 请求升级成变更 -->
    <AddChangeMask v-if="dialogVisible" ref="addChangeMask" type="upgrade" @add="upgradeChange"></AddChangeMask>
    <!-- 选择用户弹窗 -->
    <SelectUserMask ref="selectUserMask" :group-no="assignTechniciansForm.groupNo" @change="selectUserChange"></SelectUserMask>
    <!-- 用户信息 -->
    <UserInfoMask ref="userInfoMask"></UserInfoMask>
    <!-- 选择部门 -->
    <SelectDepartment ref="selectDepartmentMask" :title="selectDepartmentTitle" @change="departmentChange"></SelectDepartment>
  </div>
</template>

<script setup lang="ts" name="DetailsMask">
import { ref, watch, reactive, computed } from "vue";

import { ElMessage, ElMessageBox } from "element-plus";
import { Search } from "@element-plus/icons-vue";

import {
  findRequestByIdByClient,
  requestAction,
  openProcess,
  processHandle,
  checkEmail,
  toEmail,
  saveSolutions,
  assignTask,
  dataDictionaryItemsFindByCode
} from "@/api/modules/eventManagement";
import { getProcessImage, processDetail, getProcessInstance ,findAllHistoryRecordByClient} from "@/api/modules/common";

import SelectUserMask from "@/components/SelectUserMask/index.vue";
import EnclosureList from "@/components/EnclosureList/index.vue";
import TaskListBox from "@/components/TaskListBox/index.vue";
import HistoricalRecordsBox from "@/components/HistoricalRecordsBox/index.vue";
import ProcessHistoryTasksBox from "@/components/ProcessHistoryTasksBox/index.vue";
import EmailListBox from "@/components/EmailListBox/index.vue";
import AddProblemMask from "@/components/Problem/AddProblemMask.vue";
import AddChangeMask from "@/components/Change/AddChangeMask.vue";
import UserInfoMask from "@/components/UserInfoMask/index.vue";
import SelectDepartment from "@/components/SelectDepartment/SelectDepartment.vue";

import { useUserStore } from "@/stores/modules/user";
import { requestAllOptions } from "@/stores/modules/event";
import WangEditor from "@/components/WangEditor/index.vue";
import { dataDictionaryItemsfindByCode, getCategoryTreeAllData } from "@/api/modules/dataDictionary";
import { findFormCustomById } from "@/api/modules/systemTools";
import Custemerselect from "@/views/tools/custemerSelect/index.vue";
import { Base64 } from "js-base64";
import { useAuthButtons } from "@/hooks/useAuthButtons";

// 页面按钮权限（按钮权限既可以使用 hooks，也可以直接使用 v-auth 指令，指令适合直接绑定在按钮上，hooks 适合根据按钮权限显示不同的内容）
const { BUTTONS } = useAuthButtons();

//自定义表单回显
const showCustomerForm = ref(false);
const edescFlag = ref(false);
const formCreateRules = ref<any>([]);
const formCreateRules2 = ref<any>([]);
const customerContent = ref("");
const cwangEditor = ref(null);
const option = ref({
  submitBtn: false
});
const option2 = ref({
  submitBtn: false
});
const dataFlagObj = ref<any[]>([]);
const formData = ref<any>({
  createdByNo: "",
  etitle: "",
  requestCategoryNo: "",
  companyNo: "",
  creator: "",
  approvalNo: "",
  companyName: "",
  createdByName: "",
  requestCategoryName: "",
  imodeNo: "",
  priorityNo: "",
  effectRangeNo: "",
  levelNo: "",
  seriousnessNo: "",
  locationName: "",
  locationNos: ""
});
//自定义表单回显结束

const allOptions = requestAllOptions();
console.log(allOptions);
const userStore = useUserStore();
const dialogVisible = ref(false);
const details = ref<any>({});
const tabName = ref("info");
const tabHistory = ref<string[]>([]); // tab切换历史
const loading = ref(false);

const processDetailData = ref<any>({});

// 请求退回 / 描述完成重新提交 / 挂起 / 解除挂起
const requestActionMask = ref(false);
const requestActionMaskTitle = ref("");
const requestActionForm = reactive({
  optType: "",
  logDetails: "",
  logTitle: ""
});
const showRequestActionMask = type => {
  requestActionForm.optType = type;
  requestActionMask.value = true;
  switch (type) {
    case "notComprehensiveNotSubmitted":
      requestActionMaskTitle.value = "请求退回";
      requestActionForm.logTitle = "请求退回";
      break;
    case "request_notComprehensiveNotSubmitted":
      requestActionMaskTitle.value = "描述完成重新提交";
      requestActionForm.logTitle = "描述完成重新提交";
      break;
    case "requestHangRemove":
      if (details.value.statusCode == "request_awaiting") {
        requestActionMaskTitle.value = "解除挂起";
        requestActionForm.logTitle = "解除挂起";
      } else {
        requestActionMaskTitle.value = "挂起";
        requestActionForm.logTitle = "挂起";
      }
      break;
    case "requestGet":
      requestActionMaskTitle.value = "请求提取";
      break;
    case "reopen":
      requestActionMaskTitle.value = "流程重新开启";
      break;
    case "taskGet":
      requestActionMaskTitle.value = "任务提取";
      break;
    default:
      break;
  }
};
const requestActionLoading = ref(false);
const hang = ref(false);
const requestActionSubmit = e => {
  // if (!requestActionForm.logDetails) {
  //   ElMessage.warning("请输入备注");
  //   return false;
  // }
  requestActionLoading.value = true;
  if (e === "任务提取") {
    assignTask({
      "processHandleDTO.pid": details.value.pid,
      "processHandleDTO.eno": details.value.eno,
      "processHandleDTO.module": "request",
      "processHandleDTO.operator": userStore.username,
      "processHandleDTO.handleType": "TaskTake",
      "processHandleDTO.assignType": processDetailData.value.flowActivityDTO.assignType,
      "processHandleDTO.allowUseDynamicAssignee": false,
      "processHandleDTO.allowUseVariablesAssignee": false,
      "processHandleDTO.taskId": processDetailData.value.taskId, // 任务id
      "processHandleDTO.assigneeNo": userStore.userInfo.userId,
      "processHandleDTO.remark": requestActionForm.logDetails
    })
      .then(() => {
        requestActionLoading.value = false;
        ElMessage.success("操作成功");
        requestActionMask.value = false;
        getData();
      })
      .catch(() => {
        requestActionLoading.value = false;
      });
    return;
  }

  if (e === "挂起") {
    hang.value = true;
  } else if (e === "解除挂起") {
    hang.value = false;
  }

  requestAction({
    "requestDTO.eno": details.value.eno,
    "historyRecordDto.operator": userStore.username,
    "requestDTO.currentUser": userStore.username,
    "requestDTO.pid": details.value.pid,
    "requestDTO.requestCode": details.value.requestCode,
    "requestDTO.processNextStep": "",
    "historyRecordDto.logTitle": requestActionForm.logTitle,
    "requestDTO.optType": requestActionForm.optType,
    "historyRecordDto.logDetails": requestActionForm.logDetails,
    "requestDTO.hang": hang.value
  })
    .then(() => {
      requestActionLoading.value = false;
      ElMessage.success("操作成功");
      requestActionMask.value = false;
      getData();
    })
    .catch(() => {
      requestActionLoading.value = false;
    });
};

// 开启流程
const openProcessMask = ref(false);
const openProcessForm = reactive({
  emailAddress: "",
  remark: ""
});
const showOpenProcessMask = () => {
  for (const key in openProcessForm) {
    openProcessForm[key] = "";
  }
  openProcessMask.value = true;
};
// 开启流程提交
const openProcessLoading = ref(false);
const openProcessSubmit = () => {
  // if (!openProcessForm.remark) {
  //   ElMessage.warning("请输入流程备注");
  //   return false;
  // }
  openProcessLoading.value = true;
  openProcess({
    "processHandleDTO.operator": userStore.username,
    "processHandleDTO.pid": details.value.pid,
    "processHandleDTO.taskId": processDetailData.value.taskId,
    "processHandleDTO.eno": details.value.eno,
    "processHandleDTO.assignType": "",
    "processHandleDTO.outcome": "",
    "processHandleDTO.nextActivityType": "task",
    "processHandleDTO.allowUseDynamicAssignee": false,
    "processHandleDTO.flowActivityId": "",
    "processHandleDTO.approverTask": false,
    "processHandleDTO.module": "request",
    "processHandleDTO.variablesAssigneeType": "",
    "processHandleDTO.leaderNum": 0,
    "processHandleDTO.allowUseVariablesAssignee": false,
    "processHandleDTO.variablesAssigneeGroupNo": 0,
    "processHandleDTO.variablesAssigneeGroupName": "",
    "processHandleDTO.mailHandlingProcess": false,
    "processHandleDTO.activityName": "",
    "processHandleDTO.remark": openProcessForm.remark,
    "processHandleDTO.groupNo": "", // 组
    "processHandleDTO.assigneeNo": "", // 技术员
    "processHandleDTO.approversMemberSet": "",
    "processHandleDTO.approverResult": true,
    "processHandleDTO.emailAddress": openProcessForm.emailAddress
  })
    .then(() => {
      openProcessLoading.value = false;
      ElMessage.success("操作成功");
      openProcessMask.value = false;
      getData();
    })
    .catch(() => {
      openProcessLoading.value = false;
    });
};

// 处理完成
const processingCompletedMask = ref(false);
const processingCompletedForm = reactive({
  emailAddress: "",
  remark: ""
});
const showProcessingCompletedMask = () => {
  for (const key in processingCompletedForm) {
    processingCompletedForm[key] = "";
  }
  processingCompletedMask.value = true;
};
// 处理完成提交
const processingCompletedLoading = ref(false);
const processingCompletedSubmit = () => {
  processingCompletedLoading.value = true;
  processHandle({
    "processHandleDTO.operator": userStore.username, // 登录名
    "processHandleDTO.pid": details.value.pid,
    "processHandleDTO.eno": details.value.eno,
    "processHandleDTO.taskId": processDetailData.value.taskId,
    "processHandleDTO.assignType": "",
    "processHandleDTO.outcome": "处理完成",
    "processHandleDTO.nextActivityType": "",
    "processHandleDTO.allowUseDynamicAssignee": false,
    "processHandleDTO.flowActivityId": processDetailData.value.flowActivityDTO.id,
    "processHandleDTO.approverTask": false,
    "processHandleDTO.module": "request",
    "processHandleDTO.variablesAssigneeType": "",
    "processHandleDTO.leaderNum": 0,
    "processHandleDTO.allowUseVariablesAssignee": false,
    "processHandleDTO.variablesAssigneeGroupNo": 0,
    "processHandleDTO.variablesAssigneeGroupName": "",
    "processHandleDTO.mailHandlingProcess": false,
    "processHandleDTO.activityName": processDetailData.value.flowActivityDTO.activityName,
    "processHandleDTO.remark": processingCompletedForm.remark, // 备注
    "processHandleDTO.groupNo": "",
    "processHandleDTO.assigneeNo": details.value.assigneeNo, // 技术员
    "processHandleDTO.approversMemberSet": "",
    "processHandleDTO.approverResult": true,
    "processHandleDTO.emailAddress": processingCompletedForm.emailAddress // 通知邮箱
  })
    .then(() => {
      processingCompletedLoading.value = false;
      ElMessage.success("操作成功");
      processingCompletedMask.value = false;
      getData();
    })
    .catch(() => {
      processingCompletedLoading.value = false;
    });
};

// 指派组
// const props1 = {
//   checkStrictly: true,
//   label: "data",
//   value: "attr"
// };
// const groupList = computed(() => {
//   let list = JSON.parse(JSON.stringify(allOptions.groupList));
//   console.log(allOptions.groupList);
//   // list.forEach(item => {
//   //   item.label = item.orgName;
//   //   item.value = item.orgNo;
//   //   if (item.children) {
//   //     item.children.forEach(vo => {
//   //       vo.label = vo.orgName;
//   //       vo.value = vo.orgNo;
//   //       if (vo.children) {
//   //         vo.children.forEach(v => {
//   //           v.label = v.orgName;
//   //           v.value = v.orgNo;
//   //         });
//   //       }
//   //     });
//   //   }
//   // });
//   return list;
// });
const selectDepartmentType = ref("");
const selectDepartmentTitle = ref("");
const selectDepartmentMask = ref();
const assigneeGroupName = ref("");
const selectDepartment = (type: string, title: string) => {
  selectDepartmentType.value = type;
  selectDepartmentTitle.value = title;
  selectDepartmentMask.value?.open();
};
const departmentChange = e => {
  switch (selectDepartmentType.value) {
    // case "filterForm.requestorOrgNo":
    //   requestorOrgName.value = e.orgName;
    //   filterForm.requestorOrgNo = e.orgNo;
    //   break;
    case "filterForm.assigneeGroupNo":
      assignTechniciansForm.groupNo = e.orgNo;
      assignTechniciansForm.groupName = e.orgName;
      assigneeGroupName.value = e.orgName;
      break;
    // case "conditionForm.propValue":
    //   conditionForm.propDisplayValue = e.orgName;
    //   conditionForm.propValue = e.orgNo;
    //   break;
    default:
      break;
  }
};

// 指派其他技术员处理
const assignTechniciansMask = ref(false);
const assignText = ref("");
// 显示指派其他技术员处理弹窗
const showAssignTechniciansMask = e => {
  assignTechniciansMask.value = true;
  assignText.value = e;
};
const assignTechniciansForm = reactive({
  remark: "", // 备注
  groupNo: "", // 技术组
  groupName: "",
  assigneeNo: "", // 技术
  assigneeName: "",
  emailAddress: "" // 邮件
});

interface TreeNode {
  // label: string;
  // value: number;
  [key: string]: any;
  children?: TreeNode[];
}

// const searchTree = (tree: TreeNode[], key: keyof TreeNode, value: any) => {
//   for (const node of tree) {
//     if (node[key] === value) {
//       return node;
//     }
//     if (node.children) {
//       const result = searchTree(node.children, key, value);
//       if (result) {
//         return result;
//       }
//     }
//   }
//   return null;
// };
const searchTree = (tree: TreeNode[], key: string, value: any): TreeNode | null => {
  for (const node of tree) {
    if (node[key] === value) {
      return node;
    }
    if (node.children) {
      const result = searchTree(node.children, key, value);
      if (result) {
        return result;
      }
    }
  }
  return null;
};
const assignTechniciansGroupName = ref("");
const getVal = (val: any) => {
  console.log(val)
  assignTechniciansForm.groupNo =val[val.length-1].orgNo;
  assignTechniciansForm.groupName = val[val.length-1].orgName;
}
// watch(
//   () => assignTechniciansGroupName.value,
//   val => {
//     console.log(typeof val)
//     if(val && val.length > 0) {
//       // let item = val[val.length-1]
//       // assignTechniciansForm.groupNo = item.orgNo;
//       // assignTechniciansForm.groupName = item.orgName;
//       let item = searchTree(groupList.value, "orgNo", val[val.length-1]);
//       console.log(item)
//       assignTechniciansForm.groupNo = item ? item.orgNo : "";
//       assignTechniciansForm.groupName = item ? item.orgName : "";
//     } else {
//       assignTechniciansForm.groupNo = "";
//       assignTechniciansForm.groupName = "";
//     }
   
//     // if (val.length == 3) {
//     //   assignTechniciansForm.groupNo = val[2];
//     //   // 根据组id获取组名
//     //   let item = searchTree(groupList.value, "value", val[2]);
//     //   console.log(item)
//     //   assignTechniciansForm.groupName = item.label;
//     // } else {
//     //   assignTechniciansForm.groupNo = "";
//     //   assignTechniciansForm.groupName = "";
//     // }
//   }
// );
console.log(assignTechniciansGroupName.value)
const assignTechniciansLoading = ref(false);
// 指派其他技术员处理提交
const assignTechniciansSubmit = () => {
  assignTechniciansLoading.value = true;
  processHandle({
    "processHandleDTO.operator": userStore.username, // 登录名
    "processHandleDTO.pid": details.value.pid,
    "processHandleDTO.eno": details.value.eno,
    "processHandleDTO.taskId": processDetailData.value.taskId,
    "processHandleDTO.assignType": processDetailData.value.flowActivityDTO.assignType,
    "processHandleDTO.outcome": outcome.value,
    "processHandleDTO.nextActivityType": "task",
    "processHandleDTO.allowUseDynamicAssignee": false,
    "processHandleDTO.flowActivityId": processDetailData.value.flowActivityDTO.id,
    "processHandleDTO.approverTask": false,
    "processHandleDTO.module": "request",
    "processHandleDTO.variablesAssigneeType": "",
    "processHandleDTO.leaderNum": 0,
    "processHandleDTO.allowUseVariablesAssignee": false,
    "processHandleDTO.variablesAssigneeGroupNo": 0,
    "processHandleDTO.variablesAssigneeGroupName": "",
    "processHandleDTO.mailHandlingProcess": false,
    "processHandleDTO.activityName": processDetailData.value.flowActivityDTO.activityName,
    "processHandleDTO.remark": assignTechniciansForm.remark,
    "processHandleDTO.groupNo": assignTechniciansForm.groupNo, // 技术组
    // assigneeGroupName: assignTechniciansForm.groupName,
    "processHandleDTO.assigneeNo": assignTechniciansForm.assigneeNo, // 技术
    // assigneeName: assignTechniciansForm.assigneeName,
    "processHandleDTO.approversMemberSet": "",
    "processHandleDTO.approverResult": true,
    "processHandleDTO.emailAddress": assignTechniciansForm.emailAddress // 邮箱
  })
    .then(() => {
      assignTechniciansLoading.value = false;
      ElMessage.success("操作成功");
      assignTechniciansMask.value = false;
      getData();
    })
    .catch(() => {
      assignTechniciansLoading.value = false;
    });
};

// 流程图
const flowChartMask = ref(false);
const flowChartUrl = ref(""); // 流程图
const flowImg = ref("");
const seeFlowChart = async () => {
  flowChartMask.value = true;
  // if (!flowChartUrl.value) {
  //   getProcessImage(details.value.processKey).then((res: any) => {
  //     flowChartUrl.value = URL.createObjectURL(res);
  //   });
  // }
  const data = await getProcessInstance(details.value.pid);
  let html = data.toString();
  let vHtml = html.replaceAll("jbpm!getProcessImage.action", "api/jbpm!getProcessImage.action");
  flowImg.value = vHtml;
};

// 任务重新指派
const taskReassignmentMask = ref(false);
const taskReassignmentForm = reactive({
  assigneeNo: "",
  remark: ""
});
const assigneeName = ref("");
// 提交重新指派
const taskReassignmentLoading = ref(false);
const taskReassignmentSubmit = () => {
  taskReassignmentLoading.value = true;
  assignTask({
    "processHandleDTO.pid": details.value.pid,
    "processHandleDTO.eno": details.value.eno,
    "processHandleDTO.module": "request",
    "processHandleDTO.operator": userStore.username,
    "processHandleDTO.handleType": "TaskReAssigne",
    "processHandleDTO.assignType": processDetailData.value.flowActivityDTO.assignType,
    "processHandleDTO.allowUseDynamicAssignee": false,
    "processHandleDTO.allowUseVariablesAssignee": false,
    "processHandleDTO.taskId": processDetailData.value.taskId, // 任务id
    "processHandleDTO.assigneeNo": taskReassignmentForm.assigneeNo,
    "processHandleDTO.remark": taskReassignmentForm.remark
  })
    .then(() => {
      taskReassignmentLoading.value = false;
      ElMessage.success("保存成功");
      taskReassignmentMask.value = false;
      taskReassignmentForm.assigneeNo = "";
      assigneeName.value = "";
      taskReassignmentForm.remark = "";
      getData();
    })
    .catch(() => {
      taskReassignmentLoading.value = false;
    });
};

// 打开选择用户弹窗
const selectUserMask = ref();
const selectUserType = ref("");
const selectUser = (type: string) => {
  selectUserType.value = type;
  if (type == "technicianNo" && !assignTechniciansForm.groupNo) {
    ElMessage.warning("请选择技术组");
    return false;
  }
  if (type != "technicianNo") {
    assignTechniciansForm.groupNo = "";
    assignTechniciansForm.groupName = "";
  }
  selectUserMask.value.open();
};

// 选择用户
const selectUserChange = user => {
  // 任务重新指派
  if (selectUserType.value == "assigneeNo") {
    taskReassignmentForm.assigneeNo = user.userId;
    assigneeName.value = user.fullName;
  }
  // 指派给其他技术
  if (selectUserType.value == "technicianNo") {
    assignTechniciansForm.assigneeNo = user.userId;
    assignTechniciansForm.assigneeName = user.fullName;
  }
};

// 处理方式列表
const handlingMethodList = ref<any>([]);
// 获取处理方式列表
dataDictionaryItemsFindByCode({}).then(res => {
  handlingMethodList.value = res;
});
// 解决方案
const solutionForm = reactive({
  offmodeNo: "", // 处理方式
  content: "" // 方案描述
});
// 提交解决方案
const solutionSubmit = () => {
  if (!solutionForm.content) {
    ElMessage.warning("请输入方案描述");
    return false;
  }
  loading.value = true;
  let data = {
    "requestDTO.eno": details.value.eno,
    "requestDTO.solutions": solutionForm.content,
    "requestDTO.attachmentStr": "",
    "requestDTO.knowledgeNo": 0
  };
  if (!details.value.offmodeNo) {
    data["requestDTO.offmodeNo"] = solutionForm.offmodeNo;
  }
  saveSolutions(data)
    .then(() => {
      loading.value = false;
      ElMessage.success("保存成功");
      getData();
    })
    .catch(() => {
      loading.value = false;
    });
};

// 邮件回复
const sendMailMask = ref();
const emailForm = reactive({
  receiveAddress: "",
  subject: "",
  content: ""
});
const showSendMailMask = () => {
  emailForm.subject = "请求处理进展:(" + details.value.requestCode + ")";
  sendMailMask.value = true;
};
const emailLoading = ref(false);
const sendEmail = async () => {
  if (!emailForm.receiveAddress) {
    ElMessage.warning("请输入收件人邮箱");
    return false;
  }
  if (!emailForm.subject) {
    ElMessage.warning("请输入邮件主题");
    return false;
  }
  if (!emailForm.content) {
    ElMessage.warning("请输入邮件内容");
    return false;
  }
  emailLoading.value = true;
  const res = await checkEmail({
    isSend: true
  });
  if ((res as any) === false) {
    ElMessage.warning("邮件发送失败，请检查邮箱是否有效或邮箱服务配置是否正确");
    emailLoading.value = false;
    return;
  } else {
    toEmail({
      "emailDto.moduleCode": details.value.requestCode,
      "emailDto.receiveAddress": emailForm.receiveAddress,
      "emailDto.subject": emailForm.subject,
      "emailDto.content": emailForm.content,
      "emailDto.description": ""
    })
      .then(() => {
        emailLoading.value = false;
        sendMailMask.value = false;
        ElMessage.success("发送成功");
      })
      .catch(() => {
        emailLoading.value = false;
      });
  }
};

// 升级成问题
const addProblemMask = ref();
const showAddProblemMask = () => {
  addProblemMask.value?.open(details.value);
};

// 升级成变更
const addChangeMask = ref();
const showAddChangeMask = () => {
  addChangeMask.value?.open(details.value);
};

// 定义 emit 事件
const emit = defineEmits<{
  change: [];
}>();

const upgradeChange = () => {
  dialogVisible.value = false;
  emit("change");
};
const processIsMyGroup = ref(false);
// 获取详情
const getData = () => {
  processIsMyGroup.value = false;
  loading.value = true;
  findRequestByIdByClient({
    "requestQueryDTO.eno": details.value.eno
  })
    .then((res: any) => {
      loading.value = false;
      res.edesc = res.edesc
        .replace(
          '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">',
          ""
        )
        .trim();
      details.value = {
        ...details.value,
        ...res
      };
      solutionForm.offmodeNo = res.offmodeNo || "";
      solutionForm.content = res.solutions.replace(/<p>/g, "").replace(/<\/p>/g, "");

      // 获取流程详情
      if (res.pid) {
        processDetail(res.pid).then((res: any) => {
          if (res.length > 0) {
            processDetailData.value = res[0].flowTaskDTO[0];
            (processDetailData.value.participationDTO as any).forEach(function (element) {
              if ((element["groupId"] = "Group_" + userStore.userInfo.orgNo)) {
                processIsMyGroup.value = true;
              }
            });
            console.log("processDetailData", processDetailData.value);
          } else {
            processDetailData.value = {};
          }
        });
      } else {
        processDetailData.value = {};
      }
      let data = details.value;
      //自定义表单回显
      if (details.value.formId != "" && details.value.formId != undefined) {
        findFormCustomById(details.value.formId).then(resFindFormCustom => {
          showCustomerForm.value = true;
          edescFlag.value = false;
          let newResFindFormCustom = JSON.parse(JSON.stringify(resFindFormCustom));
          let yyde = Base64.decode(newResFindFormCustom.formCustomContents); //解密
          // console.log(yyde);
          let a = JSON.parse(yyde);
          let formCreateRulesArray: any[] = [];
          let formCreateRules2Array: any[] = [];

          for (let i = 0; i < a.length; i++) {
            if (a[i].label != undefined && a[i].label != "") {
              showCustomerForm.value = false;
              break;
            }
            if (a[i].attrdataDictionary != null && a[i].attrdataDictionary != undefined && a[i].attrdataDictionary != "") {
              dataFlagObj.value.push(a[i]);
              //优先级priority
              dataDictionaryItemsfindByCode(a[i].attrdataDictionary).then(res => {
                let optionList = [];
                (res as any).forEach(function (element) {
                  // element["label"] = element["dname"];
                  // element["value"] = element["dname"];
                  //optionList.push({label:element["dname"],value:element["dcode"]})
                  a[i].options.push({ label: element["dname"], value: element["dcode"] });
                });
                // a[i].options=optionList
              });
            }

            if (a[i].title == "描述") {
              edescFlag.value = true;
              continue;
            }
            if (edescFlag.value == false) {
              formCreateRulesArray.push(a[i] as any);
            } else {
              formCreateRules2Array.push(a[i] as any);
            }
          }
          formCreateRules.value = formCreateRulesArray;
          formCreateRules2.value = formCreateRules2Array;

          let attrVals = data.attrVals == undefined ? {} : data.attrVals;
          setTimeout(() => {
            formData.value.creator = data.creator == undefined ? "" : data.creator;

            formData.value.approvalNo = data.approvalNo == undefined ? "" : data.approvalNo;

            formData.value.etitle = data.etitle == undefined ? "" : data.etitle;
            formData.value.companyName = data.companyName == undefined ? "" : data.companyName;
            formData.value.companyNo = data.companyNo == undefined ? 1 : data.companyNo;
            formData.value.createdByName = data.createdByName == undefined ? "" : data.createdByName;
            formData.value.createdByNo = data.createdByNo == undefined ? "" : data.createdByNo;
            formData.value.requestCategoryName = data.requestCategoryName == undefined ? "" : data.requestCategoryName;
            formData.value.requestCategoryNo = data.requestCategoryNo == undefined ? "" : data.requestCategoryNo;
            //requestCategorySelectValue.value=data.requestCategoryName==undefined?"":data.requestCategoryName;
            //addRequestTemplateFormData.edesc= data.edesc==undefined?"":data.edesc;
            customerContent.value = data.edesc == undefined ? "" : data.edesc;
            // imodeSelectValue prioritySelectValue effectRangeSelectValue levelSelectValue seriousnessSelectValue LocationSelectValue
            formData.value.imodeNo = data.imodeNo == undefined ? "" : data.imodeNo == 0 ? "" : data.imodeNo;
            formData.value.priorityNo = data.priorityNo == undefined ? "" : data.priorityNo == 0 ? "" : data.priorityNo;
            formData.value.effectRangeNo =
              data.effectRangeNo == undefined ? "" : data.effectRangeNo == 0 ? "" : data.effectRangeNo;
            formData.value.levelNo = data.levelNo == undefined ? "" : data.levelNo == 0 ? "" : data.levelNo;
            formData.value.seriousnessNo =
              data.seriousnessNo == undefined ? "" : data.seriousnessNo == 0 ? "" : data.seriousnessNo;
            formData.value.locationName = data.locationName == undefined ? "" : data.locationName;
            formData.value.locationNos = data.locationNos == undefined ? "" : data.locationNos == 0 ? "" : data.locationNos;
            Object.keys(attrVals).forEach(key => {
              for (let i = 0; i < dataFlagObj.value.length; i++) {
                if (dataFlagObj.value[i].title == key) {
                  let eavKey = dataFlagObj.value[i].field;
                  if (`${attrVals[key]}` == "true") {
                    formData.value[eavKey] = true;
                  } else {
                    if (!Number.isNaN(Number(`${attrVals[key]}`))) {
                      formData.value[eavKey] = parseInt(`${attrVals[key]}`);
                    } else {
                      //非数字
                      formData.value[eavKey] = `${attrVals[key]}`;
                    }
                  }
                }
              }
            });
          }, 2000);
        });
      } else {
        showCustomerForm.value = false;
      }
    })
    .catch(() => {
      loading.value = false;
    });
};

// 显示用户信息
const userInfoMask = ref();
const showUserInfoMask = () => {
  userInfoMask.value?.open(details.value);
};

const open = (item: any) => {
  details.value = item;
  tabName.value = "info";
  tabHistory.value = [];
  dialogVisible.value = true;
  getData();
};

watch(tabName, val => {
  tabHistory.value.push(val);
});

defineExpose({
  open
});
//执行工单流程
const outcome = ref("");
const processOutcome = (e: string) => {
  if (e === "处理完成") {
    showProcessingCompletedMask();
  } else if (e === "关闭") {
    outcome.value = e;
    showAssignTechniciansMask(e);
  } else {
    outcome.value = e;
    showAssignTechniciansMask(e);
  }
};
//请求服务单
const requestServiceMask = ref(false);
const seeRequestService = () => {
  initServiceFormData(); // 初始化服务单数据
  requestServiceMask.value = true;
}

// 服务单表单数据
const serviceFormData = reactive({
  documentNumber: '',
  reporter: '',
  userGroup: '',
  contactInfo: '',
  location: '',
  expectedArrivalTime: "",
  serviceCatalog: '',
  slaLevel: '',
  acceptanceTime: "",
  acceptor: '',
  acceptanceChannel: '',
  responseTime: "",
  responder: '',
  completionTime: "",
  handler: '',
  handlingMethod: '',
  problemDescription: '',
  processRecords: [] as any[],
  assetType: '易耗品消耗 (设计易耗品更换,需要补充原件和新建的型号和序列号等信息)',
  relatedAssets: [],
  problemResolved: '是&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;否',
  overallRating: "",
  attitudeRating: "",
  skillRating: "",
  otherComments: '',
  userDepartment: '',
  userSignature: '',
  serviceUnit: '',
  engineerSignature: ''
});

// 初始化服务单数据
const initServiceFormData = () => {
  if (details.value) {
    console.log(details.value);
    serviceFormData.documentNumber = details.value.requestCode ;
    serviceFormData.reporter = details.value.createdByName ;
    serviceFormData.userGroup = details.value.assigneeGroupName; // 默认值
    serviceFormData.contactInfo = details.value.createdByPhone ;
    serviceFormData.location = details.value.locationName ;
    serviceFormData.serviceCatalog = details.value.requestCategoryName;
    serviceFormData.slaLevel = details.value.slaLevelName ;
    serviceFormData.acceptanceChannel = details.value.imodeName ;
    serviceFormData.responseTime = details.value.responsesTime ;
    serviceFormData.responder = details.value.assigneeName ;
    serviceFormData.completionTime = details.value.closeTime ;
    serviceFormData.handler = details.value.assigneeName ;
    serviceFormData.handlingMethod = details.value.offmodeName ;
    serviceFormData.problemDescription = details.value.edesc ;
    serviceFormData.relatedAssets = details.value.cigDTO;
    findAllHistoryRecordByClient({
      "hisotryRecordDto.eno": details.value.eno,
      "hisotryRecordDto.eventType": "itsm.request"
    }).then((res: any) => {
      console.log(res)
      serviceFormData.processRecords = res;
    });
  }
};

// 保存服务单
// const saveServiceForm = () => {
//   ElMessage.success('服务单保存成功');
//   console.log('保存的服务单数据:', serviceFormData);
// };

// 打印服务单
const printServiceForm = () => {
  // 创建一个新的窗口用于打印
  const printWindow = window.open('', '_blank');
  
  // 获取服务单内容
  const serviceFormContent = document.querySelector('.service-form-container');
  
  if (printWindow && serviceFormContent) {
    // 构建打印页面的HTML
    const printHTML = `
      <!DOCTYPE html>
      <html>
      <head>
        <meta charset="utf-8">
        <title>现场技术服务单</title>
        <style>
          body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background: white;
            color: #333;
          }
          .form-header {
            text-align: center;
            margin-bottom: 30px;
            border-bottom: 2px solid #409eff;
            padding-bottom: 20px;
          }
          .form-header h2 {
            color: #409eff;
            margin: 0 0 10px 0;
            font-size: 24px;
            font-weight: bold;
          }
          .form-number {
            margin: 10px 0;
            font-size: 16px;
            font-weight: bold;
          }
          .form-section {
            margin-bottom: 30px;
            border: 2px solid #e4e7ed;
            border-radius: 8px;
            padding: 20px;
            background: #fafafa;
            page-break-inside: avoid;
          }
          .form-section h3 {
            color: #409eff;
            margin: 0 0 20px 0;
            font-size: 18px;
            font-weight: bold;
            border-bottom: 1px solid #e4e7ed;
            padding-bottom: 10px;
          }
          .info-table {
            margin: 0 auto;
            margin-bottom: 15px;
          }
          .info-table th {
            background: #f5f7fa;
            color: #409eff;
            font-weight: bold;
            text-align: center;
            border: 1px solid #e4e7ed;
            padding: 12px 15px;
          }
          .info-table td {
            background: #fff;
            border: 1px solid #e4e7ed;
            padding: 12px 15px;
            font-size: 14px;
            color: #606266;
          }
          .info-table tr:hover td {
            background: #f5f7fa;
          }
          @media print {
            body {
              margin: 0;
              padding: 0;
            }
            .form-section {
              border: 1px solid #000;
              margin-bottom: 20px;
              page-break-inside: avoid;
            }
          }
        </style>
      </head>
      <body>
        ${serviceFormContent.innerHTML}
      </body>
      </html>
    `;
    
    // 写入内容到新窗口
    printWindow.document.open();
    printWindow.document.write(printHTML);
    printWindow.document.close();
    
    // 等待内容加载完成后打印
    printWindow.onload = () => {
      printWindow.focus();
      printWindow.print();
      printWindow.close();
    };
    
    ElMessage.success('正在打印服务单');
  } else {
    ElMessage.error('打印失败，请重试');
  }
};
</script>

<style lang="scss" scoped>
:deep(.el-drawer__body) {
  padding-top: 10px;
}
.btns {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  .el-button {
    margin: 4px 8px 4px 0;
  }
}
.title {
  margin-bottom: 10px;
  font-weight: bold;
}
.liu-cheng-img {
  display: block;
  width: 100%;
  min-height: 300px;
}
.flex-1 {
  flex: 1;
  overflow: hidden;
}
.color-red {
  color: #ff0000;
}

/* 服务单样式 */
.service-form-container {
  padding: 20px;
  background: #fff;
}

.form-header {
  text-align: center;
  margin-bottom: 30px;
  border-bottom: 2px solid #409eff;
  padding-bottom: 20px;
}

.form-header h2 {
  color: #409eff;
  margin: 0 0 10px 0;
  font-size: 24px;
  font-weight: bold;
}

.form-number {
  margin: 10px 0;
  font-size: 16px;
  font-weight: bold;
}

.form-note {
  color: #666;
  font-size: 14px;
  font-style: italic;
}

.form-section {
  margin-bottom: 30px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 20px;
  background: #fafafa;
}

.form-section h3 {
  color: #409eff;
  margin: 0 0 20px 0;
  font-size: 18px;
  font-weight: bold;
  border-bottom: 1px solid #e4e7ed;
  padding-bottom: 10px;
}

.satisfaction-ratings {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.rating-item {
  display: flex;
  align-items: center;
  gap: 15px;
}

.rating-item span {
  min-width: 60px;
  font-weight: bold;
}

.dialog-footer {
  text-align: right;
}

.dialog-footer .el-button {
  margin-left: 10px;
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background: #f5f7fa;
  color: #409eff;
  font-weight: bold;
}

/* 信息表格样式 */
.info-table {
  // width: 98%;
  margin: 0 auto;
  margin-bottom: 15px;
}

.info-table :deep(.el-table__body tr td) {
  background: #fff;
  border: 1px solid #e4e7ed;
  padding: 12px 15px;
  font-size: 14px;
  color: #606266;
}

.info-table :deep(.el-table__header th) {
  background: #f5f7fa;
  color: #409eff;
  font-weight: bold;
  text-align: center;
  border: 1px solid #e4e7ed;
  padding: 12px 15px;
}

.info-table :deep(.el-table__body tr:hover td) {
  background: #f5f7fa;
}

/* 表单样式优化 */
:deep(.el-form-item__label) {
  font-weight: bold;
  color: #606266;
}

:deep(.el-input__inner) {
  border-radius: 6px;
}

:deep(.el-textarea__inner) {
  border-radius: 6px;
}

/* 打印样式 */
@media print {
  .service-form-container {
    padding: 0;
    background: white;
  }
  
  .form-section {
    border: 1px solid #000;
    margin-bottom: 20px;
    page-break-inside: avoid;
  }
  
  .dialog-footer {
    display: none;
  }
}
</style>
